package com.example.springboot_sdse_air.controller;

import com.example.springboot_sdse_air.common.Result;
import com.example.springboot_sdse_air.entity.ChatMessage;
import com.example.springboot_sdse_air.entity.ChatSession;
import com.example.springboot_sdse_air.service.ChatService;
import com.example.springboot_sdse_air.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天控制器
 * 功能：处理聊天相关的API请求
 * 作者：王彬 202200111149
 * 日期：2025-01-14
 */
@CrossOrigin
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;
    private final DeepSeekService deepSeekService;

    /**
     * 创建新的聊天会话
     */
    @PostMapping("/session")
    public Result createChatSession(@RequestBody Map<String, Object> request) {
        try {
            Integer uid = (Integer) request.get("uid");
            String title = (String) request.get("title");
            Integer pdfId = (Integer) request.get("pdfId");
            
            if (uid == null || title == null || pdfId == null) {
                return Result.error("用户ID、会话标题和PDF ID不能为空");
            }
            
            Integer chatId = chatService.createChatSession(uid, title, pdfId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("chatId", chatId);
            response.put("message", "会话创建成功");
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("创建会话失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的所有聊天会话
     */
    @GetMapping("/sessions/{uid}")
    public Result getUserChatSessions(@PathVariable Integer uid) {
        try {
            List<ChatSession> sessions = chatService.getUserChatSessions(uid);
            return Result.success(sessions);
        } catch (Exception e) {
            return Result.error("获取会话列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取会话的所有消息
     */
    @GetMapping("/messages/{chatId}")
    public Result getChatMessages(@PathVariable Integer chatId) {
        try {
            List<ChatMessage> messages = chatService.getChatMessages(chatId);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error("获取消息列表失败: " + e.getMessage());
        }
    }

    /**
     * 发送消息并获取AI回复（流式）
     */
    @GetMapping(value = "/send", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sendMessage(@RequestParam Integer chatId, 
                                   @RequestParam Integer uid, 
                                   @RequestParam String message) {
        try {
            if (chatId == null || uid == null || message == null) {
                return Flux.just("错误：参数不完整");
            }
            
            // 保存用户消息
            chatService.saveChatMessage(chatId, "user", message);
            
            // 调用AI服务获取回复
            StringBuilder aiResponseBuilder = new StringBuilder();
            
            return deepSeekService.streamResponse(message)
                    .doOnNext(aiResponse -> {
                        // 累积AI回复
                        if (!aiResponse.equals("[DONE]")) {
                            aiResponseBuilder.append(aiResponse);
                        }
                    })
                    .doOnComplete(() -> {
                        // 流式回复完成后，保存完整的AI回复
                        String fullAiResponse = aiResponseBuilder.toString();
                        if (!fullAiResponse.isEmpty()) {
                            chatService.saveChatMessage(chatId, "ai", fullAiResponse);
                        }
                    })
                    .concatWith(Flux.just("[DONE]"));
                    
        } catch (Exception e) {
            return Flux.just("错误：" + e.getMessage());
        }
    }

    /**
     * 更新会话状态
     */
    @PutMapping("/session/{chatId}/state")
    public Result updateChatSessionState(@PathVariable Integer chatId, @RequestBody Map<String, String> request) {
        try {
            String state = request.get("state");
            if (state == null) {
                return Result.error("状态不能为空");
            }
            
            chatService.updateChatSessionState(chatId, state);
            return Result.success("状态更新成功");
        } catch (Exception e) {
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户在指定PDF下的最新活跃会话
     */
    @GetMapping("/session/latest/{uid}/{pdfId}")
    public Result getLatestSessionByPdf(@PathVariable Integer uid, @PathVariable Integer pdfId) {
        try {
            ChatSession session = chatService.getLatestActiveSessionByPdf(uid, pdfId);
            if (session != null) {
                return Result.success(session);
            } else {
                return Result.success(null);
            }
        } catch (Exception e) {
            return Result.error("获取会话失败: " + e.getMessage());
        }
    }
} 